import SwiftUI
import CoreLocation
import MapKit

struct NearbyView: View {
    @StateObject private var locationManager = LocationManager()
    @State private var nearbyLocations: [NearbyLocation] = []
    @State private var showingMap = false
    @State private var selectedLocation: NearbyLocation?
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 当前位置信息
                CurrentLocationView(locationManager: locationManager)
                    .padding(.horizontal)
                    .padding(.top)
                
                // 附近地点列表
                if locationManager.authorizationStatus == .authorizedWhenInUse {
                    ScrollView {
                        LazyVStack(spacing: 16) {
                            ForEach(nearbyLocations) { location in
                                NearbyLocationCard(location: location) {
                                    selectedLocation = location
                                    showingMap = true
                                }
                            }
                        }
                        .padding()
                    }
                } else {
                    // 权限未授权时的提示
                    VStack(spacing: 20) {
                        Image(systemName: "location.slash")
                            .font(.system(size: 60))
                            .foregroundColor(.gray)
                        
                        Text("需要位置权限")
                            .font(.title2)
                            .fontWeight(.semibold)
                        
                        Text("为了显示附近的地点，请允许应用访问您的位置信息")
                            .font(.body)
                            .foregroundColor(.secondary)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal)
                        
                        PrimaryButton(title: "开启位置权限", action: {
                            locationManager.requestLocationPermission()
                        })
                        .padding(.horizontal)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                }
            }
            .navigationTitle("附近")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { showingMap = true }) {
                        Image(systemName: "map")
                    }
                }
            }
            .sheet(isPresented: $showingMap) {
                NearbyMapView(
                    userLocation: locationManager.location,
                    nearbyLocations: nearbyLocations,
                    selectedLocation: selectedLocation
                )
            }
            .onAppear {
                loadNearbyLocations()
            }
            .onChange(of: locationManager.location) { _, _ in
                loadNearbyLocations()
            }
        }
    }
    
    private func loadNearbyLocations() {
        // 模拟数据 - 后续会从LocationService获取
        guard let userLocation = locationManager.location else { return }
        
        nearbyLocations = [
            NearbyLocation(
                name: "星巴克咖啡",
                distance: 0.2,
                category: "咖啡店",
                photoCount: 5,
                coordinates: CLLocationCoordinate2D(
                    latitude: userLocation.coordinate.latitude + 0.001,
                    longitude: userLocation.coordinate.longitude + 0.001
                )
            ),
            NearbyLocation(
                name: "中央公园",
                distance: 0.8,
                category: "公园",
                photoCount: 12,
                coordinates: CLLocationCoordinate2D(
                    latitude: userLocation.coordinate.latitude + 0.002,
                    longitude: userLocation.coordinate.longitude - 0.001
                )
            ),
            NearbyLocation(
                name: "购物中心",
                distance: 1.2,
                category: "购物",
                photoCount: 8,
                coordinates: CLLocationCoordinate2D(
                    latitude: userLocation.coordinate.latitude - 0.001,
                    longitude: userLocation.coordinate.longitude + 0.002
                )
            )
        ]
    }
}

// 附近地点数据模型
struct NearbyLocation: Identifiable {
    let id = UUID()
    let name: String
    let distance: Double // 公里
    let category: String
    let photoCount: Int
    let coordinates: CLLocationCoordinate2D
}

// 位置管理器
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    private let locationManager = CLLocationManager()
    
    @Published var location: CLLocation?
    @Published var authorizationStatus: CLAuthorizationStatus = .notDetermined
    
    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        authorizationStatus = locationManager.authorizationStatus
    }
    
    func requestLocationPermission() {
        locationManager.requestWhenInUseAuthorization()
    }
    
    func startUpdatingLocation() {
        locationManager.startUpdatingLocation()
    }
    
    // MARK: - CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.location = location
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        authorizationStatus = status
        if status == .authorizedWhenInUse {
            startUpdatingLocation()
        }
    }
}

// 当前位置视图
struct CurrentLocationView: View {
    @ObservedObject var locationManager: LocationManager
    
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                Text("当前位置")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                if locationManager.location != nil {
                    Text("已获取位置")
                        .font(.headline)
                        .fontWeight(.semibold)
                } else {
                    Text("正在获取位置...")
                        .font(.headline)
                        .fontWeight(.semibold)
                }
            }
            
            Spacer()
            
            Image(systemName: "location.fill")
                .foregroundColor(.accentColor)
                .font(.title2)
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }
}

// 附近地点卡片
struct NearbyLocationCard: View {
    let location: NearbyLocation
    let onTap: () -> Void
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 12) {
                // 地点图标
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color.accentColor.opacity(0.1))
                    .frame(width: 50, height: 50)
                    .overlay(
                        Image(systemName: iconForCategory(location.category))
                            .foregroundColor(.accentColor)
                    )
                
                // 地点信息
                VStack(alignment: .leading, spacing: 4) {
                    Text(location.name)
                        .font(.headline)
                        .fontWeight(.semibold)
                        .foregroundColor(.primary)
                    
                    HStack {
                        Text(location.category)
                            .font(.caption)
                            .foregroundColor(.secondary)
                        
                        Text("•")
                            .font(.caption)
                            .foregroundColor(.secondary)
                        
                        Text("\(location.photoCount) 张照片")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
                
                Spacer()
                
                // 距离信息
                VStack(alignment: .trailing, spacing: 4) {
                    Text("\(String(format: "%.1f", location.distance))km")
                        .font(.subheadline)
                        .fontWeight(.semibold)
                        .foregroundColor(.accentColor)
                    
                    Image(systemName: "chevron.right")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            .padding()
            .background(Color(.systemBackground))
            .cornerRadius(12)
            .shadow(color: Color.black.opacity(0.05), radius: 4, x: 0, y: 2)
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    private func iconForCategory(_ category: String) -> String {
        switch category {
        case "咖啡店": return "cup.and.saucer.fill"
        case "公园": return "leaf.fill"
        case "购物": return "bag.fill"
        case "餐厅": return "fork.knife"
        default: return "mappin"
        }
    }
}

// 附近地图视图
struct NearbyMapView: View {
    let userLocation: CLLocation?
    let nearbyLocations: [NearbyLocation]
    let selectedLocation: NearbyLocation?
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        NavigationView {
            ZStack {
                // 地图视图 - 这里使用占位符，实际需要集成MapKit
                RoundedRectangle(cornerRadius: 0)
                    .fill(Color(.systemGray6))
                    .overlay(
                        VStack {
                            Image(systemName: "map")
                                .font(.system(size: 60))
                                .foregroundColor(.gray)
                            Text("地图视图")
                                .font(.headline)
                                .foregroundColor(.gray)
                        }
                    )
                
                // 关闭按钮
                VStack {
                    HStack {
                        Spacer()
                        Button(action: { dismiss() }) {
                            Image(systemName: "xmark.circle.fill")
                                .font(.title2)
                                .foregroundColor(.white)
                                .background(Color.black.opacity(0.3))
                                .clipShape(Circle())
                        }
                        .padding()
                    }
                    Spacer()
                }
            }
            .navigationTitle("附近地图")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarHidden(true)
        }
    }
}

#Preview {
    NearbyView()
} 